package cn.gok.gokhappymall.portal.servie.impl;

import cn.gok.gokhappymall.dao.UserMapper;
import cn.gok.gokhappymall.portal.servie.IUserService;
import cn.gok.gokhappymall.util.ResultData;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * @Author: chenfan
 * @Description:
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    TimedCache timedCache;

    @Override
    public ResultData forgetGetQuestion(String username) {

        String question = userMapper.queryQuestionByUsername(username);
        if(StrUtil.isBlank(question)){
            return ResultData.fail("暂未创建密保问题");
        }
        return ResultData.createData(question);
    }

    @Override
    public ResultData forgetCheckAnswer(String username, String question, String answer) {
        int i = userMapper.checkUsername(username);
        if (i == 0){
            return ResultData.fail("该用户不存在，请稍后再试");
        }
        String sysAnswer = userMapper.queryAnswerByUsernameAndQuestion(username, question);

        if (StrUtil.isBlank(sysAnswer)){
            return ResultData.fail("密保验证失败，请稍后再试");
        }

        if (!sysAnswer.equals(answer)){
            return ResultData.fail("密保验证失败，请稍后再试");
        }

        String token = UUID.randomUUID().toString();

        //token 存入到缓存中
        timedCache.put(username, token);

        return ResultData.createData(token);
    }

    @Transactional
    @Override
    public ResultData forgetResetPassword(String username, String passwordNew, String forgetToken) {
        String sysToken = (String) timedCache.get(username);
        if (StrUtil.isBlank(sysToken)){
            return ResultData.fail("密码修改出现异常，请稍后再试");
        }
        if (!StrUtil.equals(sysToken,forgetToken)){
            return ResultData.fail("密码修改出现异常，请稍后再试");
        }


        //通过加密工具，对用户密码进行操作
        MD5 md5 = SecureUtil.md5();
        passwordNew  = md5.digestHex(passwordNew.getBytes());

        int i = userMapper.updatePasswordByUsername(username, passwordNew);
        if (i > 0){
            timedCache.remove(username);
            return ResultData.success("修改密码成功");
        }
        return ResultData.fail("修改密码失败，请稍后再试");
    }


}
